# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName : zsj.py
# @Time     : 2024/4/14 19:39
# @Author   : Robot-Zsj
"""
description:

i:
4
3 2 1 -3
1 -1 1 1
1 1 -1 2
-2 1 2 3

o:
9
"""

n = int(input())

queue = []

candy = [[-1] * n for _ in range(n)]

matrix = []
for i in range(n):
    matrix.append(list(map(int, input().split())))

    for j in range(n):

        if matrix[i][j] == -3:
            candy[i][j] = 0
            queue.append((i, j))

offsets = ((0, -1), (-1, 0), (1, 0), (0, 1))


def bfs():
    global queue

    ans = -1

    while len(queue) > 0:
        newQueue = []
        flag = False
        for x, y in queue:
            for offsetX, offsetY in offsets:
                newX = x + offsetX
                newY = y + offsetY

                if newX < 0 or newX >= n or newY < 0 or newY >= n or matrix[newX][newY] == -1:
                    continue

                if candy[newX][newY] == -1:
                    newQueue.append((newX, newY))

                candy[newX][newY] = max(candy[newX][newY], candy[x][y] + max(0, matrix[newX][newY]))

                if matrix[newX][newY] == -2:
                    ans = candy[newX][newY]
                    flag = True

        if flag:
            break

        queue = newQueue

    return ans


print(bfs())
